#!/usr/bin/python3
# _*_ coding: utf-8 _*_
#
# Copyright (C) 2024 - 2024 heihieyouheihei, Inc. All Rights Reserved 
#
# @Time    : 2024/9/11 17:19
# @Author  : Yuyun
# @File    : 二叉树右视图.py
# @IDE     : PyCharm
from collections import deque
class TreeNode:
    def __init__(self, val, left = None, right = None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def levelorder_traversal(self, root: TreeNode):
        if root is None:
            return
        queue = deque([root])
        res = []
        while queue:
            #   存储每层节点
            level = []
            #   遍历每层，双端队列加入每层节点的左右字节点
            for i in range(len(queue)):
                node = queue.popleft()
                #   仅添加每层最后一个节点
                if i == len(queue) - 1:
                    level.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(level)